<?php
/**
 * 数据导入类
 */
namespace Common\Utils;
class DataImport{
	public $csv_file='';

	public $group_key='';

	public $mysql_rows=array();

	public $max_rows=1000;

	public $com_cache_key='com_cache_key';

	public $debug=false;

	public $nead_row	=	array(
								'nsrsbh' 	=>	array('纳税人识别号','nsrsbh'),
								'nsrmc'  	=>	array('纳税人名称','nsrmc'),
								'zsxm'  	=>	array('征收项目','zsxm_dm'),
								'se'     	=>	array('实缴金额','se','税额'),
								'rkrq'   	=>	array('入库日期','rkrq'),
								'ly'		=>	array('来源'),
								'YSFPBL_DM'	=>	array('预算分配比例'),
							);

	public function __construct($csv_file='')
	{
		if(!empty($csv_file)) $this->csv_file=$csv_file;

		if(!file_exists($csv_file))
		{
			E($csv_file."文件不存在");
		}

		$this->group_key=time();

	}


	public function toMysql()
	{
		dump_r("开始读取文件:".$this->csv_file."的数据.");
		$f = fopen($this->csv_file,"r");
		$i=0;
		$md_revenue=D("Revenue");
		while(! feof($f))
		{
			$row=fgetcsv($f);

			$row=array_map(array($this, 'iconv_str'), $row);

			$i++;
			if($i==1)
			{
				//解析表头
				$row_key=$this->findRowKey($row);
				
				continue;
			}

			if(!is_array($row_key))
			{
				E("数据表头解析失败");
			}


			if($row[$row_key['YSFPBL_DM']]=='中央100%') continue;

			$data_row=array(
				'row_number'=>$i,
				'group_key'=>$this->group_key,
			);

			//表头处理完毕.开始处理内容
			foreach($row_key as $key=>$row_num)
			{
				$data_row[$key]=$row[$row_num];
			}

			if(empty($data_row['nsrsbh']) && empty($data_row['nsrmc'])) continue;

			$data_row['csv_data']=serialize($row);


			if($data_row['ly']=='国税')	$data_row['source']='gs';
			else $data_row['source']='ds';


			$ms_comid=$this->getMsComid($data_row['nsrsbh'],$data_row['nsrmc']);
			$data_row['mssql_comid']=$ms_comid;
			$md_revenue->checkInsertData($data_row);

			array_push($this->mysql_rows,$data_row);


			if(count($this->mysql_rows)>=$this->max_rows)
			{
				$md_revenue->addAll($this->mysql_rows);
				dump_r("当前读取到到".$i."行数据,已写入mysql.",$this->debug);
				unset($this->mysql_rows);
				$this->mysql_rows=array();
			}
		}
		dump_r("文件:".$this->csv_file."数据数据读取完毕.");
	}

	
	public function toMssql()
	{
		dump_r("开始文件:".$this->csv_file."数据写入数据库.");
		$do_key=true;
		$md_revenue=D("Revenue");
		$md_ss=D("CzjSszsxx");
		while ($do_key) {
			$insert_datas=array();
			$data_rows=$md_revenue->getNewData($this->group_key,200);

			if(empty($data_rows)) 
			{
				$do_key=false;
				continue;
			}


			foreach ($data_rows as $data_row) {

				if(empty($data_row['mssql_comid']))
				{
					$md_revenue->setOver($data_row['id'],false,'企业id异常');
					dump_r("记录[id=".$data_row['id']."]的comid异常:".$data_row['mssql_comid'],$this->debug);
					continue;
				}

				$insert_data=array(
					'zssj'=>$data_row['rkrq'],
					'zsxm'=>$data_row['zsxm'],
					'zsje'=>$data_row['se'],
					'fromid'=>$data_row['id'],
					'drbatch'=>$data_row['group_key'],
					'addtime'=>date("Y-m-d H:i:s"),
					'zscom'=>$data_row['mssql_comid'],
				);

				if($data_row['source']=='ds') $insert_data['zsdw']=1;
				else $insert_data['zsdw']=2;


				array_push($insert_datas,$insert_data);
			}


			$md_ss->addAll($insert_datas);

			$md_revenue->setAllOver($data_rows);

			dump_r("文件:".$this->csv_file."中".count($insert_datas)."条数据写入数据库.",$this->debug);


		}
		dump_r("完成文件:".$this->csv_file."数据写入数据库.");
	}

	/**
	 * 查询本次导入的结果
	 * @return [type] [description]
	 */
	public function getImportResult()
	{
		$md_revenue=D("Revenue");
		$rows=$md_revenue->field("count(id) as number,sum(se) as hjje,state")->group('state')->where(array('group_key'=>$this->group_key))->select();
		$result_str='';
		$all_number=0;
		$all_se=0;
		foreach ($rows as $row) {
			$all_number += $row['number'];
			$all_se += $row['hjje'];
			switch ($row['state']) {
				case $md_revenue::STATE_Over:
					$result_str .="导入完成的数据有".$row['number']."条,合计金额为:".$row['hjje'].";";
					break;
				case $md_revenue::STATE_err:
					$result_str .="导入失败的数据有".$row['number']."条,合计金额为:".$row['hjje'].";";
					break;
				default:
					$result_str .="导入状态为".$row['state']."的数据有".$row['number']."条,合计金额为:".$row['hjje'].";";
					break;
			}
		}

		$result_str="本次共计导入数据:".$all_number."条,合计金额为:".$all_se."元,其中:".$result_str."";


		//查询mssql里的结果
		$md_ss=D("CzjSszsxx");
		$sql="select top 1 count(ssid) as number,sum(zsje) as hjje from czj_sszsxx where drbatch='".$this->group_key."'";
		$rows=$md_ss->query($sql);
		$result_str.="数据库中查询到数据:".$rows[0]['number']."条,合计金额为:".$rows[0]['hjje'].";";

		dump_r($result_str);

	}

	/**
	 * 根据表头查询各内容列的列号
	 * @param  [type] $one_row [description]
	 * @return [type]          [description]
	 */
	protected function findRowKey($one_row,$find_v=null)
	{
		$row_key=array();
		$find_title='';
		foreach($one_row as $key=>$v)
		{
			$v=strtolower($v);

			if(!empty($find_v))
			{

				if($v==strtolower($find_v)) return $key;
			}
			else
			{
				foreach($this->nead_row as $nead_key=>$nead_v)
				{
					if(in_array($v, $nead_v))
					{
						$find_title.=$v.',';
						$row_key[$nead_key]=$key;
						continue;
					}

				}
			}

			
		}

		if(count($row_key)==count($this->nead_row))
		{
			return $row_key;
		}
		else
		{
			E("表头列不全.只找到了:".$find_title);
		}


		
		
		//print_r($row_key);
				
		//die();
	}



	protected function getMsComid($sbh,$name)
	{
		$cache_data=F($this->com_cache_key);
		$row_key=md5($sbh.$name);

		if(isset($cache_data[$row_key]))
		{
			return $cache_data[$row_key]['comid'];
		}
		else
		{
			$comid=$this->findMssqlComid($sbh,$name,true);
			if($comid==false) return false;
			
			$cache_data[$row_key]=array(
				'sbh'=>$sbh,'name'=>$name,'comid'=>$comid
			);
			F($this->com_cache_key,$cache_data);
			unset($cache_data);
			return $comid;
		}
	}



	/**
	 * 检查企业id缓存是否正确
	 * @return [type] [description]
	 */
	public function checkComCache()
	{
		dump_r("开始检查企业缓存信息.");
		$cache_data=F($this->com_cache_key);
		if(empty($cache_data))
		{
			dump_r("未发现企业缓存信息.");
			return true;
		}

		foreach ($cache_data as $key => $data) {
			if(md5($data['sbh'].$data['name'])!=$key)
			{
				unset($cache_data[$key]);
				continue;
			}

			$find_mssql_comid=$this->findMssqlComid($data['sbh'],$data['name']);

			if($find_mssql_comid != $data['comid'])
			{
				unset($cache_data[$key]);
				continue;
			}
		}

		F($this->com_cache_key,$cache_data);
		dump_r("企业缓存信息检查完毕.");
	}
	/**
	 * 去mssql里查询数据
	 * @param  [type] $sbh  [description]
	 * @param  [type] $name [description]
	 * @return [type]       [description]
	 */
	protected function findMssqlComid($sbh,$name,$insert_do=false)
	{
		$ms_md_com=D("CzjCom");

		$com_info=$ms_md_com->findInfo($sbh,$name);

		if(isset($com_info['comid'])) return $com_info['comid'];
		else 
		{
			if($insert_do)
			{
				//
				$new_id=$ms_md_com->addNewCom($sbh,$name);
				if($new_id==false) return false;
				else
				{
					dump_r("新插入一家企业,企业识别号是[$sbh],企业名称是[$name]",$this->debug);
					return $new_id;
				}

			}
			else
				return false;
		}

	}







/**
	 * 字符集转换
	 * @param  [type] $str [description]
	 * @return [type]      [description]
	 */
	
	protected function iconv_str($str)
	{
		return iconv("GBK","UTF-8",$str);
	}
}
?>